package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.Attribute;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.AttributeService;

import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * Created by liusonglin on 2016/11/21.
 */
@Log4j
@Controller
@RequestMapping("/admin/attribute")
public class AttributeController {
    @Autowired
    private AttributeService attributeService;

    @RequestMapping("/index")
    public String index(Model model){
        return "attribute";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> attributeList(Attribute attribute){
        List<Attribute> attributeList = attributeService.getAttributePage(attribute);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(attributeList);
        tableContainer.setiTotalDisplayRecords(attribute.getTotalCount());
        tableContainer.setiTotalRecords(attribute.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid Attribute attribute, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String str=sdf.format(date);
        attribute.setPostTime(str);
        boolean flag = false;
        if(attribute.getId()!=null && attribute.getId()!=0){
            flag = this.attributeService.updateAttribute(attribute);
        }else {
            flag = this.attributeService.newAttribute(attribute);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAttribute(@PathVariable("id") int id){
        boolean flag = this.attributeService.deleteAttributeById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

}
